#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include <fcntl.h>

#define ITERATIONS 10000

// 测试read函数
void test_read() {
    char buffer[1];
    int fd = open("test_read.dat", O_RDONLY);
    if (fd == -1) {
        perror("open test_read.dat failed");
        exit(EXIT_FAILURE);
    }
    for (int i = 0; i < ITERATIONS; i++) {
        read(fd, buffer, 1);
    }
    close(fd);
}

// 测试write函数
void test_write() {
    char buffer[1] = {'A'};
    int fd = open("test_write.dat", O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (fd == -1) {
        perror("open test_write.dat failed");
        exit(EXIT_FAILURE);
    }
    for (int i = 0; i < ITERATIONS; i++) {
        write(fd, buffer, 1);
    }
    close(fd);
}

// 测试fread函数
void test_fread() {
    char buffer[1];
    FILE *fp = fopen("test_read.dat", "r");
    if (fp == NULL) {
        perror("fopen test_read.dat failed");
        exit(EXIT_FAILURE);
    }
    for (int i = 0; i < ITERATIONS; i++) {
        fread(buffer, 1, 1, fp);
    }
    fclose(fp);
}

// 测试fwrite函数
void test_fwrite() {
    char buffer[1] = {'A'};
    FILE *fp = fopen("test_fwrite.dat", "w");
    if (fp == NULL) {
        perror("fopen test_fwrite.dat failed");
        exit(EXIT_FAILURE);
    }
    for (int i = 0; i < ITERATIONS; i++) {
        fwrite(buffer, 1, 1, fp);
    }
    fclose(fp);
}

int main() {
    // 准备测试文件
    FILE *fp_prep = fopen("test_read.dat", "w");
    if (fp_prep == NULL) {
        perror("fopen test_read.dat failed");
        return EXIT_FAILURE;
    }
    for (int i = 0; i < ITERATIONS; i++) {
        fputc('A', fp_prep);
    }
    fclose(fp_prep);

    // 测量时间
    struct timeval start, end;
    double time_used;

    // 测试read
    gettimeofday(&start, NULL);
    test_read();
    gettimeofday(&end, NULL);
    time_used = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
    printf("read time: %.6f seconds\n", time_used);

    // 测试write
    gettimeofday(&start, NULL);
    test_write();
    gettimeofday(&end, NULL);
    time_used = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
    printf("write time: %.6f seconds\n", time_used);

    // 测试fread
    gettimeofday(&start, NULL);
    test_fread();
    gettimeofday(&end, NULL);
    time_used = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
    printf("fread time: %.6f seconds\n", time_used);

    // 测试fwrite
    gettimeofday(&start, NULL);
    test_fwrite();
    gettimeofday(&end, NULL);
    time_used = (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1e6;
    printf("fwrite time: %.6f seconds\n", time_used);

    return 0;
}

